<?php

namespace App\Console\Commands;

use App\Jobs\VisitRecord;
use App\Models\FlowChannel;
use App\Models\OrderReadInfo;
use App\Models\Setting as SettingModel;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class FlowChannelStat extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'stat:flow_channel {date?} {hour?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '流量主定时统计';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {


        $date = $this->argument('date') ?: Carbon::now()->toDateString();
        if ($this->argument('hour') === null) {
            $hour = Carbon::now()->hour;//没传入参数，取当前小时
        } elseif ($this->argument('hour') === 0) {
            $hour = 0;
        } else {
            $hour = $this->argument('hour');
        }

        $divide_rate = SettingModel::query()->firstOrCreate(['key' => 'divide_rate'], ['value' => null]);

        $flow_channel_data = \App\Models\VisitRecord::query()->whereHas('order')->groupBy('flow_channel_id', 'order_id')->where([
            'date' => $date,
            'hour' => $hour
        ])->whereNotNull('flow_channel_id')
            ->selectRaw('flow_channel_id,order_id,count(*) as pv')->get()
            ->map(function ($visit_record) use ($date, $hour) {
                //取当前订单在当前小时段阅读增量和pv数据
                $order_read_inc = Cache::remember('order_' . $visit_record->order_id . 'd_' . $date . 'h_' . $hour . 'read_num_inc', '60', function () use ($date, $hour, $visit_record) {
                    $order_info = OrderReadInfo::query()->groupBy('order_id')->where([
                        'date' => $date,
                        'hour' => $hour,
                        'order_id' => $visit_record->order_id
                    ])->selectRaw('sum(read_num_inc) as read_num_inc,order_id')
                        ->first();
                    return $order_info;
                });
                if (is_null($order_read_inc)) {
                    //没有订单阅读增量数据，默认增量为0
                    $visit_record->read_num_inc = 0;
                    $visit_record->amount = 0;
                } else {
                    //订单有阅读增量，取当前订单当前时间总PV数据，按照PV占比计算当前渠道阅读增量
                    $order_data = Cache::remember('order_' . $visit_record->order_id . 'd_' . $date . 'h_' . $hour . 'total_pv', '60', function () use ($date, $hour, $visit_record) {
                        $order_data = \App\Models\VisitRecord::query()->where([
                            'date' => $date,
                            'hour' => $hour,
                            'order_id' => $visit_record->order_id,
                        ])->selectRaw('count(*) as total_pv')
                            ->first();
                        return $order_data;
                    });
                    $visit_record->read_num_inc = ($visit_record->pv / $order_data->total_pv) * $order_read_inc->read_num_inc;//根据PV占比计算阅读增量
                    $visit_record->amount = ($visit_record->read_num_inc / 1000) * $order_read_inc->order->cpm;//根据阅读增量计算产值
                }
                return $visit_record;
            });

        $flow_channel_data->groupBy('flow_channel_id')->each(function ($item, $key) use (&$data, $date, $hour, $divide_rate) {

            //计算当前流量主的在当前时段的IP数
            $ip_num = \App\Models\VisitRecord::query()->where([
                'date' => $date,
                'hour' => $hour,
                'flow_channel_id' => $key
            ])
                ->distinct()->count('ip');
            $uv_num = \App\Models\VisitRecord::query()->where([
                'date' => $date,
                'hour' => $hour,
                'flow_channel_id' => $key
            ])
                ->distinct()->count('u_id');
            $flow_channel = FlowChannel::query()->findOrFail($key);
            \App\Models\FlowChannelStat::query()->updateOrCreate([
                'date' => $date,
                'hour' => $hour,
                'flow_channel_id' => $key
            ], [
                'divide_amount' => ($item->sum('amount') * json_decode($divide_rate->value) / 100) * $flow_channel->rate / 100,
                'read_num_incr' => $item->sum('read_num_inc'),
                'pv' => $item->sum('pv'),
                'ip_num' => $ip_num,
                'uv_num' => $uv_num
            ]);
        });

    }
}

